using System.Collections.Generic;
using System.Threading.Tasks;
using AvaloniaMvvm.Helpers;
using AvaloniaMvvm.Models;
using SQLite;

namespace AvaloniaMvvm.Services;

public class PoetryStorage : IPoetryStorage {
    public const string DbName = "poetrydb.sqlite3";

    public static readonly string PoetryDbPath =
        PathHelper.GetLocalFilePath(DbName);

    private SQLiteAsyncConnection _connection;

    private SQLiteAsyncConnection Connection =>
        _connection ??= new SQLiteAsyncConnection(PoetryDbPath);

    public async Task InsertAsync(Poetry poetry) =>
        await Connection.InsertAsync(poetry);

    public async Task<IList<Poetry>> ListAsync() =>
        await Connection.Table<Poetry>().ToListAsync();

    public async Task<IList<Poetry>> QueryAsync(string keyword) =>
        await Connection.Table<Poetry>().Where(p => p.Name.Contains(keyword)).ToListAsync();
}